<template>
	<ls-page title="">
		<view class="feedback-container">
			<view class="feedback-container-type">
				<view class="feedback-title">
					<view class="feedback-h2">问题类型</view>
				</view>
				<view class="feedback-value" @click="typeShow=true">
					<view class="value-text">选择类型</view>
					<view class="value-right">
						<view class="right-value">{{typeText}}</view>
						<view class="right-icon"></view>
					</view>
				</view>
			</view>
			<view class="feedback-container-position">
				<view class="feedback-title">
					<view class="feedback-h2">位置</view>
					<view class="feedback-h3">（选填）</view>
				</view>
				<view class="feedback-value" @click="tableShow=true">
					<view class="value-text">选择桌号</view>
					<view class="value-right">
						<view class="right-value">{{tableText}}</view>
						<view class="right-icon"></view>
					</view>
				</view>
			</view>
			<view class="feedback-container-question">
				<view class="feedback-title">
					<view class="feedback-h2">问题和建议</view>
				</view>
				<van-cell-group>
					<van-field v-model="postForm.feedBackContent" type="textarea" placeholder="请输入问题和建议" autosize
						:border="false" maxlength="100" show-word-limit custom-class="textarea"
						input-class="textarea-input" />
				</van-cell-group>
			</view>
			<view class="feedback-container-photo">
				<view class="feedback-title">
					<view class="feedback-h2">图片</view>
					<view class="feedback-h3">（选填）</view>
				</view>
				<view class="uploader">
					<up-upload :fileList="fileList" @afterRead="afterRead" @delete="deletePic" name="6" width="105" height="105" multiple>
						<image src="https://oss.jtmckj.com/h5-uniapp/blanKarea/coupon/upload-icon.png" mode="widthFix"
							style="width: 200rpx;height: 200rpx;"></image>
					</up-upload>
				</view>
			</view>
			<view class="feedback-container-btn">
				<view class="btn-item" @click="submit">提交</view>
			</view>
		</view>
		<up-picker :show="typeShow" :closeIcon="false" title="选择类型" ref="uPickerRef" keyName="name"
			@close="typeShow = false" :closeOnClickOverlay="true" @cancel="typeShow = false" :columns="typeColumns"
			@confirm="typeConfirm"></up-picker>
		<x-popup :show="tableShow" position="bottom" @close="tableShow = false" :closeOnClickOverlay="true" @update:show="tableShow = $event">
			<view class="popup-container">
				<view class="popup-container-header">
					<view class="header-left" @click="tableShow = false">取消</view>
					<view class="header-center">选择桌号</view>
					<view class="header-right" @click="tableConfirm">确认</view>
				</view>
				<!-- 选择区域 -->
				<view class="popup-container-main">
					<van-col span="6" class="main-item" v-for="(item, index) in list" :key="index">
						<view class="main-item-one" :class="{
							          'selected': currentArea === index, 
							          'unselected': currentArea !== index
							        }" @click="selectArea(index)">
							{{ item.areaName }}
						</view>
					</van-col>
				</view>
				<!-- 选择桌号 -->
				<view class="popup-container-footer" v-if="currentArea !== null">
					<view class="footer-item" @click="selectTable(index)"
						v-for="(table, index) in list[currentArea].children" :key="index" :class="{
						      'selected': currentTable === index, 
						      'unselected': currentTable !== index
						    }">
						{{ table.name }}
					</view>
				</view>
			</view>
		</x-popup>
	</ls-page>
</template>

<script setup>
	import { ref, reactive } from 'vue';
	import { onLoad, onUnload, onShow, onHide } from '@dcloudio/uni-app';
	import setting from "@/common/config.js";
	import { HFiveAppObjProcess, HFiveMemberAppObjProcess } from '@/api/public.js'
    
	// -------------------------------------------------------初始化数据-----------------------------------------------------
	const shopInfo = uni.getStorageSync('shopInfo') //门店信息
	const userInfo = uni.getStorageSync('userInfo') //用户信息

	//当前选中的区域索引
	const currentArea = ref(0);
	// 初始化数据
	const isHidden = ref(true);
	const typeShow = ref(false);
	const tableShow = ref(false);
	const typeText = ref('');
	const tableText = ref('');
	const typeColumns = ref([]);	

	// 提交反馈的参数
	const postForm = ref({
		proType: '',
		roomCode: '',
		feedBackContent: '',
		attachment: ''
	});
	// 文件列表
	const fileList = ref([]);
	// 使用中桌台
	const list = ref([]);
	const current = ref(0);
	const currentTable = ref(0);
	const selectedTable = ref({})
	// -------------------------------------------------------初始化数据-----------------------------------------------------

	onLoad((options) => {
		getQuesstions()
		getRoomTable()
	})

	onShow(() => {
		const pages = getCurrentPages();
		console.log(pages, 'dfsada')
		// 检查当前页面的路径并设置 backFn
		if (pages[0].route === 'pages/account/firing/firing' || pages[0].route ===
			'pages/center/centerStore/index') {
			backFn.value = () => {
				// 执行跳转到首页
				uni.reLaunch({
					url: '/pages/home/index'
				});
			};
		}
	});

	// 显示问题类型选择
	const pickType = () => {
		typeShow.value = !typeShow.value;
	};

	// 取消选择问题类型
	const typeCancel = () => {
		typeText.value = '';
		typeShow.value = !typeShow.value;
	};

	// 确认选择问题类型
	const typeConfirm = (e) => {
		postForm.value.proType = e.value[0].code;
		typeText.value = e.value[0].name;
		typeShow.value = !typeShow.value;
	};

	// 显示桌台选择
	const pickTable = () => {
		tableShow.value = true;
	};

	// 关闭桌台选择
	const closeTable = () => {
		tableShow.value = false;
	};

	// 选择桌台
	const selectTab = (e) => {
		if (e.target.value) {
			currentTable.value = e.target.value;
		}
	};

	// 选择区域
	const selectArea = (index) => {
		currentArea.value = index;
		currentTable.value = 0;
	};

	// 选择桌台
	const selectTable = (index) => {
		currentTable.value = index;
	};
	
	
	// ---------------------------------------------------------获取问题类型----------------------------------------------------------
	const getQuesstions = async () => {
		try {
			const res = await HFiveMemberAppObjProcess({
				functionName: 'GetDicData_H5',
				contentData: { parentCode: '564' },
			});
			typeColumns.value = [res];
		} catch (err) {
			console.error('获取问题类型失败:', err);
		}
	};
	
	// ---------------------------------------------------------获取桌台列表----------------------------------------------------------
	const getRoomTable = () => {
		HFiveMemberAppObjProcess({ "functionName": "GetRoomOpWine_H5", "contentData": { "consumeState": "" } })
			.then(res => {
				list.value = res
				console.log(list.value, 'ist.value');
			})
	}

    // ---------------------------------------------------------桌台确认----------------------------------------------------------
	const tableConfirm = () => {
		if (currentArea.value !== null && currentTable.value !== null) {
			const selectedArea = list.value[currentArea.value];
			selectedTable.value = selectedArea.children[currentTable.value];
			console.log('选中的区域:', selectedArea.areaName);
			console.log('选中的桌台:', selectedTable.value.name);
			console.log('桌台编码:', selectedTable.value.code);
			postForm.value.roomCode = selectedTable.value.code
			tableText.value = selectedTable.value.name
			tableShow.value = false
			// 你可以根据需要在这里执行进一步的操作，比如传递数据或显示提示
		} else {
			console.log('请选择区域和桌台');
		}
	}
    
	// ---------------------------------------------------------提交表单----------------------------------------------------------
	const submit = () => {
		// 将文件 URL 拼接成字符串
		const urlArray = fileList.value.map((file) => file.url);
		const urlStr = urlArray.join(',');
		postForm.value.attachment = urlStr;
	
		if (postForm.value.feedBackContent === '') {
			uni.$u.toast('问题和建议不能为空')
			return;
		}
	
		HFiveMemberAppObjProcess({
			functionName: 'CreateFeedBack_H5',
			contentData: postForm.value
		}).then((res) => {
			const msg = res;
			uni.$u.toast('提交成功')
			setTimeout(() => {
				uni.navigateBack();
			}, 1500)
	
		});
	};

	// ---------------------------------------------------------上传图片----------------------------------------------------------

	// 删除图片
	const deletePic = (event) => {
		fileList.value.splice(event.index, 1);
	};

	// 新增图片
	const afterRead = async (event) => {
		console.log(event)
		// 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
		let lists = [].concat(event.file);
		let fileListLen = fileList.value.length;
		lists.map((item) => {
			fileList.value.push({
				...item,
				status: 'uploading',
				message: '上传中',
			});
		});
		for (let i = 0; i < lists.length; i++) {
			const result = await uploadFilePromise(lists[i].url,lists[i].name);
			let item = fileList.value[fileListLen];
			fileList.value.splice(fileListLen, 1, {
				...item,
				status: 'success',
				message: '',
				url: result,
			});
			fileListLen++;
		}
	};

	const uploadFilePromise = (url,name) => {
		return new Promise((resolve, reject) => {
			let a = uni.uploadFile({
				url: setting.PRO_URL + '/api/upload', // 仅为示例，非真实的接口地址
				filePath: url,
				name: 'data',
				formData: {
					requestId: Math.random().toString(36).substr(2, 8),
					total: 1,
					fileName: name,
					objName: 'Mini',
					orgCode: '004',
					uploadType: 'OSS',
					bucketName: 'jtmc',
				},
				success: (res) => {
					// setTimeout(() => {
					// }, 1000);
					let data = JSON.parse(res.data)
					resolve(data.content.urlPath);
				},
			});
		});
	};
</script>

<style scoped lang="less">
	.feedback-container {
		width: 100%;
		height: 100%;
		overflow: scroll;
		box-sizing: border-box;
		padding: 0 24rpx;

		.feedback-title {
			display: flex;
			align-items: center;
			padding: 40rpx 0;

			.feedback-h2 {
				font-family: PingFang SC;
				font-weight: bold;
				font-size: 32rpx;
				color: var(--maincolorf1);
				line-height: 32rpx;
			}

			.feedback-h3 {
				font-family: PingFang SC;
				font-weight: bold;
				font-size: 24rpx;
				color: var(--maincolorf2);
				line-height: 24rpx;
			}
		}

		.feedback-value {
			background: var(--maincolor);
			border-radius: 16rpx;
			padding: 45rpx 40rpx;
			display: flex;
			align-items: center;
			justify-content: space-between;

			.value-text {
				font-family: PingFang SC;
				font-weight: 500;
				font-size: 32rpx;
				color: var(--maincolorf2);
				line-height: 32rpx;
			}

			.value-right {
				display: flex;
				align-items: center;

				.right-value {
					font-family: PingFang SC;
					font-weight: 500;
					font-size: 32rpx;
					color: var(--maincolorf1);
					line-height: 32rpx;
					padding-right: 16rpx;
				}

				.right-icon {
					width: 12rpx;
					height: 22rpx;
					background-image: url('https://oss.jtmckj.com/wmp/images/center/i_icon_tra-right.png');
					background-size: 100% 100%;
					background-repeat: no-repeat;
				}
			}
		}

		.feedback-container-type {}

		.feedback-container-position {}

		.feedback-container-question {
			.feedback-h2 {
				padding-right: 25rpx;
				position: relative;

				&::before {
					content: '';
					position: absolute;
					top: 0;
					right: 0;
					width: 18rpx;
					height: 16rpx;
					background-image: url('https://oss.jtmckj.com/wmp/images/center/i_icon_star.png');
					background-size: 100% 100%;
					background-repeat: no-repeat;
				}
			}

			.textarea {
				background: var(--second--back-color);
				border-radius: 16rpx;
				padding: 33rpx 40rpx 20rpx;
			}

			.van-cell__value {
				color:var(--maincolorf1) !important;
			}

			.textarea-input {
				height: 120rpx !important;
				font-family: PingFang SC;
				font-weight: 500;
				font-size: 28rpx;
				color:var(--maincolorf1) !important;
				line-height: 42rpx;
			}

			.van-field__placeholder {
				color: var(--maincolorf4) !important;
			}

			.van-field__word-num {
				color:var(--maincolorf1) !important;
			}
		}

		.feedback-container-photo {
			margin-bottom: 20rpx;

			.uploader {
				padding: 24rpx;
				background: var(--maincolor);
				border-radius: 16rpx;

				.van-uploader__upload {
					background: var(--maincolorf6);
					border-radius: 8px;
					width: 202rpx !important;
					height: 202rpx !important;
				}

				.van-uploader__preview-image {
					width: 202rpx !important;
					height: 202rpx !important;
				}

				.van-icon--image {
					width: 40rpx;
					height: 40rpx;
				}
			}
		}

		.feedback-container-btn {
			margin-top: 40rpx;
			margin-bottom: 60rpx;

			.btn-item {
				text-align: center;
				// background: #3D6652;
				background: var(--dt-backcolorPink);
				border-radius: 40rpx;
				font-family: PingFang SC;
				font-weight: 500;
				font-size: 32rpx;
				// color: var(--third--self--color);
				color: var(--maincolor);
				line-height: 32rpx;
				padding: 25rpx 0;
			}
		}
	}

	.popup-container {
		padding-bottom: 40rpx;
		background: var(--maincolor);

		.popup-container-header {
			display: flex;
			align-items: center;
			justify-content: space-between;
			// padding: 33rpx 60rpx 32rpx;
			border-bottom: 1rpx solid var(--maincolorbd);

			.header-left {
				font-family: PingFang SC;
				font-weight: 500;
				font-size: 32rpx;
				color: var(--maincolor);
				line-height: 32rpx;
				padding: 33rpx 60rpx 32rpx;
			}

			.header-center {
				font-family: PingFang SC;
				font-weight: bold;
				font-size: 36rpx;
				color: var(--maincolorf1);
				line-height: 36rpx;
			}

			.header-right {
				font-family: PingFang SC;
				font-weight: 500;
				font-size: 32rpx;
				color: var(--maincolorf1);
				line-height: 32rpx;
				padding: 33rpx 60rpx 32rpx;
			}
		}

		.popup-container-main {
			margin-top: 20rpx;
			display: flex;
			align-items: center;
			justify-content: flex-start;
			flex-wrap: wrap;

			.main-item {
				border-radius: 8rpx;
				font-family: PingFang SC;
				font-weight: 500;
				font-size: 32rpx;
				color: var(--maincolorf1);
				line-height: 80rpx;
				text-align: center;

				.main-item-one {
					background:var(--mainbaccolor5);
					border-radius: 8rpx;
					margin-right: 10rpx;
				}
			}

			.van-col {
				margin-bottom: 20rpx;
			}

		}

		.popup-container-footer {
			background: var(--mainbaccolor);
			border-radius: 16rpx;
			padding: 10rpx 0rpx 4rpx 10rpx;
			display: flex;
			align-items: center;
			justify-content: flex-start;
			flex-wrap: wrap;

			.footer-item {
				width: 118rpx;
				height: 60rpx;
				background: var(--mainbaccolor5);
				border-radius: 8rpx;
				text-align: center;
				margin-bottom: 20rpx;
				font-family: PingFang SC;
				font-weight: 500;
				font-size: 28rpx;
				color: var(--maincolor);
				line-height: 60rpx;
				margin-right: 14rpx;
				white-space: nowrap;
			}
		}
	}

	.selected {
		color: var(--maincolor);
		background: var(--maincolorf1) !important;
	}

	.unselected {
		color: var(--maincolorf1) !important;
		background: var(--mainbaccolor5) !important;
	}

	::v-deep .van-field__control {
		font-size: 32rpx;
		color: var(--maincolorf1);
	}

	::v-deep .van-field__control::placeholder {
		font-family: PingFang SC;
		font-weight: 500;
		font-size: 32rpx;
		color: var(--maincolorf2);
		line-height: 32rpx;
	}

	::v-deep .u-popup__content {
		border-radius: 30rpx 30rpx 0 0;
	}

	::v-deep .popup-content {
		padding-top: 0 !important;
	}

	::v-deep .u-picker .u-toolbar__wrapper__cancel {
		color: var(--maincolorf2) !important;
	}

	::v-deep .u-picker .u-toolbar__wrapper__confirm {
		color: var(--maincolorf1) !important;
	}
</style>